<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\SmsLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yunpian\Sdk\YunpianClient;


class PhoneVerificationsController extends Controller
{
    public function send(Request $request)
    {
//        检测该手机号是否超过发送数量限制,返回true表示没有超过
        if ($this->maximumNumberLimit($request->input('phone_number'))) {
            $phoneVerification = SmsLog::create([
                'code' => rand(1111, 9999),
                'type' => 'bind',
                'phone_number' => $request->input('phone_number'),
            ]);
            $res = $this->sendSMS($phoneVerification->phone_number, $phoneVerification->code, $phoneVerification->type);

            if ($res->code() == 0) {
                return response()->json(['code' => 1, 'message' => '验证短信成功发送']);
            } elseif ($res->code() == 2) {
                $phoneVerification->delete();
                return response()->json(['code' => 1002, 'message' => '手机号错误'], 400);
            } else {
                $phoneVerification->delete();
                return response()->json(['code' => 1001, 'message' => $res->code()], 400);
            }
        }

        return response()->json(['code' => 1003, 'message' => '该手机号已超过发送限制次数，请稍后'], 400);
    }

//    检测是否超过数量限制,返回true表示没有超过
    public function maximumNumberLimit($phone_number)
    {
        $num = SmsLog::query()->where('phone_number', $phone_number)->whereBetween('created_at', [Carbon::now(), Carbon::now()->addHours(1)])->count();
        return (int)$num < 5;
    }

    private function sendSMS($phone_number, $code, $type)
    {
        $text = [
            'bind' => '【YOUNG学生折】亲爱的大学生朋友，欢迎加入HeyYoung！您的验证码为：' . $code . '。为了你的账号安全，请及时输入进行验证。',
        ];
        $client = YunpianClient::create(Setting::getValue('YUNPIAN_API_KEY'));
        $param = [
            YunpianClient::MOBILE => '+86' . $phone_number,
            YunpianClient::TEXT => $text[$type]
        ];
//        执行发送
        $r = $client->sms()->single_send($param);
        return $r;
    }
}
